package com.molichuxing.framework.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;

/**
 * @project_name: utils
 * @description: cookie工具类
 * @author: 林亿建
 * @create_date: 2016年1月11日
 * @modify_date: 2016年1月11日
 */
public final class CookieUtil {

  private final Logger logger = LoggerFactory.getLogger(CookieUtil.class);

  private HttpServletRequest request;

  private HttpServletResponse response;

  public CookieUtil(HttpServletRequest req, HttpServletResponse res) {
    request = req;
    response = res;
  }

  /**
   * 获取某个cookie值
   *
   * @param name cookie名
   * @return cookie值
   */
  public String getCookieValue(String name) {
    Cookie[] cookies = request.getCookies();

    if (cookies == null) {
      return null;
    }

    Cookie cookie = null;
    for (int i = 0; i < cookies.length; i++) {
      cookie = cookies[i];
      if (cookie.getName().equalsIgnoreCase(name)) {
        return cookie.getValue();
      }
    }
    return null;
  }

  /**
   * 设置cookie值
   *
   * @param name cookie名
   * @param value cookie值
   * @param domain cookie所在域
   * @param expire 过期时间（秒）
   */
  public void setCookie(String name, String value, String domain, int expire) {
    Cookie cookie = new Cookie(name, value);
    cookie.setDomain(domain);
    cookie.setPath("/");

    if (expire >= 0) {
      cookie.setMaxAge(expire);
    }
    response.addCookie(cookie);
  }

  /**
   * 设置cookie
   *
   * @param name cookie名称
   * @param value cookie值
   * @param expire 过期时间
   * @author Jin Miao
   */
  public void setCookie(String name, String value, int expire) {
    Cookie cookie = new Cookie(name, value);
    cookie.setMaxAge(expire);

    response.addCookie(cookie);
  }

  /**
   * 设置cookie值
   *
   * @param name cookie名
   * @param value cookie值
   * @param domain cookie所在域
   */
  public void setCookie(String name, String value, String domain) {
    setCookie(name, value, domain, -1);
  }

  /**
   * 清除指定域下的cookie
   *
   * @param name cookie名
   * @param domain cookie所在域
   */
  public void clearCookie(String name, String domain) {
    setCookie(name, "", domain, 0);
  }

  /**
   * 清除指定域下所有cookie
   */
  public void clearAllCookie() {
    Cookie[] cookies = request.getCookies();
    for (int i = 0; i < cookies.length; i++) {
      cookies[i].setValue(null);
    }

  }

  /**
   * 获取某个cookie所在的域信息
   *
   * @param name cookie名
   * @return
   */
  public String getCookieDomain(String name) {
    Cookie[] cookies = request.getCookies();
    if (cookies == null) {
      return null;
    }

    Cookie cookie = null;
    for (int i = 0; i < cookies.length; i++) {
      cookie = cookies[i];
      if (cookie.getName().equalsIgnoreCase(name)) {
        logger.error(cookie.getDomain());
        return cookie.getDomain();
      }
    }
    return null;
  }

  /**
   * 获取cookie信息
   *
   * @param name
   * @return
   */
  public Cookie getCookie(String name) {
    Cookie[] cookies = request.getCookies();
    if (cookies == null) {
      return null;
    }

    Cookie cookie = null;
    for (int i = 0; i < cookies.length; i++) {
      cookie = cookies[i];
      if (cookie.getName().equalsIgnoreCase(name)) {
        return cookie;
      }
    }
    return null;
  }

  /**
   * 判断COOKIE是否过期
   *
   * @param strDate 上次访问的时间，格式：yyyy-MM-dd HH:mm:ss
   * @param minutes 过期时间（以分为单位）
   * @return true 过期 false 未过期
   */
  public static boolean isCookieExpire(String strDate, int minutes) {
    Calendar c = Calendar.getInstance();
    int year = Integer.parseInt(strDate.substring(0, 4));
    int month = Integer.parseInt(strDate.substring(5, 7)) - 1;
    int day = Integer.parseInt(strDate.substring(8, 10));
    int hour = Integer.parseInt(strDate.substring(11, 13));
    int minute = Integer.parseInt(strDate.substring(14, 16));
    int second = Integer.parseInt(strDate.substring(17));
    c.set(year, month, day, hour, minute, second);
    c.add(Calendar.MINUTE, minutes);
    return c.before(Calendar.getInstance());
  }

}
